<template>
  <el-upload
    :file-list="fileList"
    action="#"
    list-type="picture-card"
    :class="{disable:fileList.length>0}"
    :on-remove="onRemove"
    :on-change="onChange"
    :before-upload="beforeUpload"
    :http-request="httpRequest"
  >
    <i class="el-icon-plus" />
  </el-upload>
</template>

<script>
// 引入包
import COS from 'cos-js-sdk-v5'
// 创建实例
const cos = new COS({
  SecretId: 'AKID5zeikgPtBLHzTihZNwGJerzwjIgsqb7N',
  SecretKey: 'CAvRhkZ9hGiyzmMrGVfiidWXTL8Thrsk'
})
export default {
  data() {
    return {
      fileList: []
    }
  },
  methods: {
    onRemove(file, newFileList) { this.fileList = newFileList },
    onChange(file, newFileList) {
      this.fileList = newFileList
    },

    beforeUpload(file) {
      const whiteList = ['image/jpeg', 'image/png']
      if (whiteList.indexOf(file.type) === -1) {
        this.$message.error('当前仅支持jpeg/png文件')
        return false
      }
      //   大小校验
      const maxSize = 1 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('文件不能大于1M')
        return false
      }
    },
    httpRequest(params) {
      console.log('真正上传功能')
      cos.putObject({
        Bucket: 'hr-upload-data-1317163428', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: 'params.file.name', /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: params.file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        console.log('没有error就是成功')
        console.log(err || data)
        if (!err) {
          this.fileList[0].url = 'http://' + data.Location
          this.fileList[0].status = 'success'
        }
      })
    }
  }

}
</script>

<style lang="scss" scoped>
.disable{::v-deep .el-upload--picture-card{
    display:none;
}}

</style>
